package com.test.controller;

import com.test.po.User;
import com.test.service.UserService;
import com.test.vo.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by Lenovo on 2019/1/9.
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin.do")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login.do")
    @ResponseBody
    public Result login(String userName, String password, boolean isChecked, HttpServletRequest request){
        UsernamePasswordToken token = new UsernamePasswordToken(userName, DigestUtils.md5Hex(password));
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            boolean rememberme = isChecked ? true : false;
            token.setRememberMe(rememberme);
        }catch (UnknownAccountException e){
            e.printStackTrace();
            return Result.fail(403,"用户名不存在");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return Result.fail(403,"密码不正确");
        }
        System.out.println("==================登录成功=====================");
        return Result.sucessd("home.do");
    }

    @RequestMapping("/logout.do")
    @ResponseBody
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        System.out.println("=====================注销成功===================");
        return Result.sucessd("index.jsp");
    }

    @RequestMapping("/home.do")
    public String manageUI(HttpServletRequest request) {
        //主体
        Subject subject = SecurityUtils.getSubject();

        User user = (User) subject.getPrincipal();

        request.setAttribute("loginUser", user);

        return "manageUI";
    }

}
